<?php
require_once __DIR__ . '/../../functions.php';

header('Content-Type: application/json');

// 检查管理员权限
if (!isAdmin()) {
    echo json_encode(['success' => false, 'message' => '您没有权限执行此操作']);
    exit;
}

// 获取POST数据
$input = json_decode(file_get_contents('php://input'), true);
$settlementId = intval($input['settlement_id'] ?? 0);
$filename = $input['filename'] ?? '';

if ($settlementId <= 0 || empty($filename)) {
    echo json_encode(['success' => false, 'message' => '参数无效']);
    exit;
}

$db = getDB();

// 获取当前结算信息
$stmt = $db->prepare("SELECT settlement_screenshots FROM settlements WHERE id = ?");
$stmt->execute([$settlementId]);
$settlement = $stmt->fetch();

if (!$settlement) {
    echo json_encode(['success' => false, 'message' => '结算记录不存在']);
    exit;
}

// 处理截图
$currentScreenshots = [];
if (!empty($settlement['settlement_screenshots'])) {
    $screenshots = json_decode($settlement['settlement_screenshots'], true);
    if (is_array($screenshots) && !empty($screenshots)) {
        $currentScreenshots = $screenshots;
    }
}

// 删除指定截图
$newScreenshots = array_filter($currentScreenshots, function($screenshot) use ($filename) {
    return $screenshot !== $filename;
});

// 删除物理文件
deleteFile($filename, 'settlement_screenshot');

// 更新数据库
$stmt = $db->prepare("UPDATE settlements SET settlement_screenshots = ?, updated_at = NOW() WHERE id = ?");
if ($stmt->execute([json_encode(array_values($newScreenshots)), $settlementId])) {
    echo json_encode(['success' => true, 'message' => '截图删除成功']);
} else {
    echo json_encode(['success' => false, 'message' => '截图删除失败']);
}
?>